<template>
  <div class="container">
    <div class="flex flex-wrap f-ptp10">
      <!-- <el-select class='f-mrt20 f-mbt10 f-w120' v-model="vip" clearable placeholder="请选择">
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
      </el-select>-->
      <el-input class="f-mrt20 f-mbt10 f-w250" clearable v-model="id" placeholder="订单号"></el-input>
      <el-input class="f-mrt20 f-mbt10 f-w250" clearable v-model="mobileNo" placeholder="手机号码"></el-input>
      <el-select
        @change="sourceChangeEvent"
        class="f-mrt20 f-mbt10 f-w120"
        v-model="source"
        placeholder="请选择"
      >
        <el-option
          v-for="item in sourceList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <el-date-picker
        class="f-mrt20 f-mbt10 f-w120"
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      ></el-date-picker>
      <el-button class="f-h40" @click="getList" type="primary">查询</el-button>
      <el-button class="f-h40" @click="exportBtnClickEvent" type="success">导出excel</el-button>
    </div>
    <div style="padding: 0 0 20px 0;">
      <el-radio-group @change="getList" v-model="accountType" size="small">
        <el-radio-button v-if="source != 'recharge'" label="all">全部</el-radio-button>
        <el-radio-button label="user">用户</el-radio-button>
        <el-radio-button v-if="source != 'recharge'" label="lawyer">律师</el-radio-button>
      </el-radio-group>
    </div>
    <div>
      <el-table :data="tableData" border style="width: 1111px">
        <el-table-column prop="id" label="交易订单号" width="210"></el-table-column>
        <el-table-column prop="userId" label="用户ID" width="180"></el-table-column>
        <el-table-column prop="mobileNo" label="用户手机" width="180"></el-table-column>
        <!-- <el-table-column prop="type" label="交易类型" width="180"></el-table-column> -->
        <el-table-column prop="amount" label="交易金额" width="180">
          <template slot-scope="scope">
            <span>￥{{formatPrice(scope.row.amount)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="交易时间" width="180">
          <template slot-scope="scope">
            <span>{{format(scope.row.createTime)}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="totalCount > 0" class="f-ptp20 f-pbt20">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          background
          :total="totalCount"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  name: "TradeRecordManage",
  data() {
    return {
      mobileNo: "",
      type: "out",
      sourceList: [
        {
          label: "公益支付",
          value: "project"
        },
        {
          label: "充值支付",
          value: "recharge"
        },
        {
          label: "案件支付",
          value: "lawyerCase"
        }
      ],
      accountType: "all",
      source: "lawyerCase",
      id: "", // 订单编号
      password: "",
      tableData: [],
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      date: null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 导出按钮点击事件
    exportBtnClickEvent() {
      if (this.totalCount > 0) {
        this.getAllList();
      }
    },
    // 导出所有数据
    exportAllExcel(list) {
      console.log("list::", list);
      console.log(XLSX.utils.encode_cell({ c: 4, r: list.length + 1 }));
      let sheet1 = {
        "!ref": "A1:" + XLSX.utils.encode_cell({ c: 4, r: list.length + 1 }),
        A1: { v: "交易订单号", t: "s" },
        B1: { v: "用户id", t: "s" },
        C1: { v: "用户手机", t: "s" },
        D1: { v: "交易金额", t: "s" },
        E1: { v: "交易时间", t: "s" },
      };
      for (let i = 0; i < list.length; i++) {
        let column_1 = XLSX.utils.encode_cell({ c: 0, r: i + 1 });
        let column_2 = XLSX.utils.encode_cell({ c: 1, r: i + 1 });
        let column_3 = XLSX.utils.encode_cell({ c: 2, r: i + 1 });
        let column_4 = XLSX.utils.encode_cell({ c: 3, r: i + 1 });
        let column_5 = XLSX.utils.encode_cell({ c: 4, r: i + 1 });
        sheet1[column_1] = {
          v: list[i].id,
          t: "s"
        };
        sheet1[column_2] = {
          v: list[i].userId,
          t: "s"
        };
        sheet1[column_3] = {
          v: list[i].mobileNo,
          t: "s"
        };

        sheet1[column_4] = {
          v: '￥' + list[i].amount,
          t: "s"
        };
        sheet1[column_5] = {
          v: list[i].createTime,
          t: "d"
        };
    
      }
      console.log("sheet1:::", sheet1);
      const workbook = {
        FileName: "export.xlsx",
        SheetNames: ["Sheet1"],
        Sheets: {
          Sheet1: sheet1
        }
      };
      const workbookOut = XLSX.write(workbook, {
        bookType: "xlsx",
        bookSST: false,
        type: "array"
      });
      var date = new Date();
      var fileName =
        "交易记录_" +
        date.getFullYear() +
        "_" +
        (date.getMonth() + 1) +
        "_" +
        date.getDate() +
        ".xlsx";
      try {
        FileSaver.saveAs(
          new Blob([workbookOut], {
            type: "application/octet-stream"
          }),
          fileName
          // "user.xlsx"
        ); //trade-publish.xlsx 为导出的文件名
      } catch (e) {
        console.log(e, workbookOut);
      }
      return workbookOut;
    },

    sourceChangeEvent() {
      if (this.source == "recharge") {
        this.accountType = "user";
      }
      this.getList();
    },
    format(date) {
      return this._utils.format(date, "yyyy-mm-dd");
    },
    formatPrice(price) {
      return this._utils.formatPrice(price);
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getList();
    },
    getCaseType(caseType) {
      console.log("caseType:::", caseType);
    },
    tranDate(date) {
      return this._utils.format(date, "yyyy-mm-dd");
    },
    getList() {
      /*   source string  project("公益支付"), recharge("充值支付"), lawyerCase("案件支付");
       *   type   string  in ：收入 ， out：支出
       */

      const _this = this;
      const params = {
        source: this.source,
        // type: this.type,
        id: this.id,
        pageNum: this.currentPage - 1,
        pageSize: this.pageSize,
        mobileNo: this.mobileNo
      };
      if (this.accountType != "all") {
        params.accountType = this.accountType;
      }

      if (
        this._utils.getType(this.date) === "Array" &&
        this.date.length === 2
      ) {
        params.startDay = this._utils.format(this.date[0], "yyyy-mm-dd");
        params.endDay = this._utils.format(this.date[1], "yyyy-mm-dd");
      }

      this.$store
        .dispatch("GET_LOG_CAPITAL", params)
        .then(res => {
          if (res.data.retCode == 0) {
            _this.tableData = res.data.data.logList;
            _this.totalCount = res.data.data.totalCount;
          } else {
            res.data.errorMsg && this.$message.warning(res.data.errorMsg);
          }
        })
        .catch(err => {
          console.error("获取问题列表：：", err);
        });
    },
    getAllList() {
      /*   source string  project("公益支付"), recharge("充值支付"), lawyerCase("案件支付");
       *   type   string  in ：收入 ， out：支出
       */

    //   const _this = this;
      const params = {
        source: this.source,
        // type: this.type,
        id: this.id,
        pageNum: 0,
        pageSize: this.totalCount,
        mobileNo: this.mobileNo
      };
      if (this.accountType != "all") {
        params.accountType = this.accountType;
      }

      if (
        this._utils.getType(this.date) === "Array" &&
        this.date.length === 2
      ) {
        params.startDay = this._utils.format(this.date[0], "yyyy-mm-dd");
        params.endDay = this._utils.format(this.date[1], "yyyy-mm-dd");
      }

      this.$store
        .dispatch("GET_LOG_CAPITAL", params)
        .then(res => {
          if (res.data.retCode == 0) {
            this.exportAllExcel(res.data.data.logList);
          } else {
            this.$message.warning('获取导出数据发生错误！');
          }
        })
        .catch(err => {
            this.$message.warning('获取导出数据发生错误！');
          console.error("获取问题列表：：", err);
        });
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.top {
  /* display: flex; */
  overflow: hidden;
  padding: 10px 0;
}

.top-item {
  float: left;
  margin-right: 20px;
}

.w-120 {
  width: 120px;
}

.w-200 {
  width: 200px;
}
</style>
